<template>
  <div v-if="!printShow">
    <div class="front">
      <el-collapse v-model="activeNames" class="front-collapse"
        @change="activeNames = !activeNames; collapseName == '收起' ? collapseName = '展开' : collapseName = '收起'"
        style="width: 100%;">
        <el-collapse-item :title="collapseName" class="collapse-1" name="1">
          <el-form :model="searchForm" label-width="120px">
            <el-form-item label="出库单号" class="front-input">
              <el-input v-model="searchForm.orderCode" />
            </el-form-item>
            <el-form-item label="出库类型" class="front-input">
              <el-select v-model="searchForm.orderType" placeholder="请选择出库类型" style="" prop="clientId">
                <el-option label="销售出库" value="0" />
                <el-option label="借货出库" value="1" />
                <el-option label="还货出库" value="2" />
                <el-option label="加工出库" value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="所属仓库" class="front-input">
              <el-select v-model="searchForm.warehouseId" placeholder="搜索匹配" style="">
                <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName"
                  :value="item.warehouseId" />
              </el-select>
            </el-form-item>
            <el-form-item label="出库客户" class="front-input">
              <el-select v-model="searchForm.clientId" placeholder="搜索匹配" style="" prop="clientId">
                <el-option v-for="item in clientList" :key="item.id" :label="item.clientName" :value="item.id" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
              <el-button type="primary" @click="onReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- <div class="center">
        <el-col>
          <el-text class="center-data">出库总数量</el-text>
          <el-text class="center-data">出库总成本价</el-text>
        </el-col>
      </div> -->

    <div class="tail">
      <div class="tail-action">
        <el-button type="primary" @click="handlerExportOrder">导出明细</el-button>
        <el-button type="primary" @click="printSelectedRows">直接打印出库单</el-button>
        <el-button type="primary" @click="designPrint">自定义打印出库单</el-button>
        <el-button type="primary">打印明细</el-button>
        <el-button type="primary" @click="mergeOrder">合并出库单</el-button>
        <el-popover placement="bottom" trigger="click">
          <template #reference>
            <el-button><el-icon>
                <List />
              </el-icon>显示设置</el-button>
          </template>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="selectedFilters" @change="handleCheckChange">
            <el-checkbox v-for="item in tableFilter.map(i => i.label)" :label="item" :key="item" />
          </el-checkbox-group>
        </el-popover>
      </div>
      <el-table :data="tableData()" border style="width: 100%" :max-height="collapseName == '收起' ? 400 : 700"
        @selection-change="handleChangeSelection" v-loading="tableLoading">
        <template v-slot:empty>
          <div class="no-data">暂无数据</div>
        </template>
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column v-for="item in outboundDataColumn" :prop="item.prop" :min-width="item.minWidth" :width="item.width"
          :max-width="item.maxWidth" :label="item.label">
          <template v-if="true" v-slot:default="scope">
            <!-- 价格类型 -->
            <div v-if="item.prop == 'settlementType'">
              <el-tag v-if="scope.row[item.prop] == 2" type="success">成本价百分比</el-tag>
              <el-tag v-else-if="scope.row[item.prop] == 1" type="info">标签价百分比</el-tag>
            </div>
            <!-- 出库类型 -->
            <div v-else-if="item.prop == 'orderType'">
              <span v-if="scope.row[item.prop] == 0">销售出库</span>
              <span v-if="scope.row[item.prop] == 1">市场还货</span>
              <span v-if="scope.row[item.prop] == 2">客户借货</span>
            </div>  
            <!-- 时间格式化 -->
            <div v-else-if="item.prop == 'updateTime'">
              <span>{{ parseTimestamp(scope.row[item.prop]) }}</span>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope" style="flex: auto;">
            <el-button link type="primary" size="small" @click="openDetails(scope.row)">查看明细</el-button>
            <!-- <el-button link type="primary" size="small">编辑备注</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
          layout="prev, pager, next ,total,sizes" :total="data.total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
    <div class="dialog-list">
      <!-- <div>
        <el-drawer v-model="drawer" :direction="direction" size="35%">
          <el-descriptions border size="large" direction="vertical" title="出库单详情">
            <el-descriptions-item label="出库单号">{{ rowDetails.orderCode }}</el-descriptions-item>
            <el-descriptions-item label="数量">{{ rowDetails.jadeWeight }}</el-descriptions-item>
            <el-descriptions-item label="供应商" width="150">{{ rowDetails.supplierName }}</el-descriptions-item>
            <el-descriptions-item label="客户名字">{{ rowDetails.clientName }}</el-descriptions-item>
            <el-descriptions-item label="仓位名字" width="150">{{ rowDetails.storageName }}</el-descriptions-item>
            <el-descriptions-item label="仓库名字">{{ rowDetails.warehouseName }}</el-descriptions-item>
            <el-descriptions-item label="入库时间">{{ rowDetails.createTime }}</el-descriptions-item>
            <el-descriptions-item label="添加人">{{ rowDetails.createBy }}</el-descriptions-item>
            <el-descriptions-item label="修改时间">{{ rowDetails.updateTime }}</el-descriptions-item>
            <el-descriptions-item label="修改人">{{ rowDetails.updateBy }}</el-descriptions-item>
          </el-descriptions>
        </el-drawer>
      </div> -->

      <div>
        <el-dialog v-model="drawer" width="80%" title="出库单明细">
          <el-table :data="rowDetails" border size="80%" max-height="500">
            <el-table-column prop="imageUrl" label="图片">
              <template v-slot:default="scope">
                <img :src="'http://8.134.106.197:9001/profile' + scope.row.imageUrl" alt="图片"
                  style="max-width: 100%; max-height: 100px;" />
              </template>
            </el-table-column>

            <el-table-column prop="outboundOrderCode" label="出库单编码" min-width="100" />
            <el-table-column prop="storageName" label="出库的仓位名称" min-width="60" />
            <!-- <el-table-column prop="jadeName" label="翡翠品类名称" min-width="60" /> -->
            <el-table-column prop="jadeCode" label="翡翠编码" min-width="60" />
            <el-table-column prop="jadeBarcode" label="条形码" min-width="60" />
            <el-table-column prop="outboundCount" label="出库数量" min-width="60" />
            <el-table-column prop="delFlag" label="删除标志" min-width="60" />
            <el-table-column prop="remark" label="备注" min-width="150" />
          </el-table>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="drawer = false">取消</el-button>
              <el-button type="primary" @lcick="drawer = false">
                确定
              </el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
  <div v-else>
    <a-button @click="printShow = false" type="primary" danger>退出打印页面</a-button>
    <print :provider="providerData" :printData="printDataProp"></print>
  </div>
</template>
  
<script>
import { defineComponent, reactive, toRefs, ref } from "vue";
import '@/mock/outbound.js'
import { onMounted } from "vue";
import { getOutboundOrderList, mergeOutboundOrder, exportOutboundOrder} from '@/api/outbound/outbound'
import { getClientList } from "@/api/user/user"
import { onBeforeMount } from "vue";
import { getWarehouseListV2 } from '@/api/setting/setting';
import { ElMessage } from "element-plus";
import { List } from '@element-plus/icons-vue';
//打印界面
import print from '@/print/index.vue'
//打印标签组成
import provider from '@/api/outbound/order/orderProvider.js'
import { createElementTypes, printData } from '@/api/outbound/order/orderProvider.js'
export default defineComponent({
  name: "HomeView",
  components: {
    List,
    print
  },
  setup() {
    //将打印标签界面传给print子组件
    const providerData = ref(provider)
    const printDataProp = ref(printData)
    const printShow = ref(false)

    const rowDetails = ref({})
    const drawer = ref(false)
    const checkAll = ref(true)
    const isIndeterminate = ref(false)
    const searchForm = reactive({  //出库搜索表单
      orderCode: '',
      clientId: '',
      warehouseId: '',
      orderType: ''
    })
    const selectedRows = ref([])
    const outboundOrderData = ref([]);
    const clientList = ref([])//客户列表
    const warehouseList = ref([])//仓库列表
    const selectedFilters = ref([])
    const outboundDataColumn = ref([])
    const tableFilter = ref([//表头自定义数组
      { label: '出库单单号', prop: 'orderCode', width: '230', isdisabled: true, isSelected: true },
      { label: '入库单单号', prop: 'inboundOrderCode', width: '230', isdisabled: true, isSelected: true },
      { label: '出库客户', prop: 'clientName', width: '100', isdisabled: true, isSelected: true },
      { label: '出库数量', prop: 'outboundSumCount', width: '100', isSelected: true },
      { label: '出库类型', prop: 'orderType', width: '100', isdisabled: true, isSelected: true },
      { label: '仓库编号', prop: 'warehouseId', width: '150', isdisabled: true, isSelected: true },
      { label: '仓库名称', prop: 'warehouseName', width: '150', isdisabled: true, isSelected: true },
      // { label: '状态', prop: 'status', width: '100', isdisabled: true, isSelected: true },
      { label: '出库人员', prop: 'createBy', width: '100', isdisabled: true, isSelected: true },
      { label: '供应商名称', prop: 'supplierName', width: '100', isdisabled: true, isSelected: true },
      { label: '出借天数', prop: 'lendDays', width: '110', isdisabled: true, isSelected: true },
      { label: '结算方式', prop: 'settlementType', width: '160', isdisabled: true, isSelected: true },
      { label: '结算比率', prop: 'settlementRatio', width: '100', isdisabled: true, isSelected: true },
      // { label: '销售时间', prop: 'validDate', minWidth: '100', isdisabled: true, isSelected: true },
      { label: '出库时间', prop: 'updateTime', minWidth: '200', isdisabled: true, isSelected: true },
      { label: '备注', prop: 'remark', width: '190', isSelected: true },
    ])

    const collapseName = ref('展开');
    const activeNames = ref(false)

    //表格用到的参数
    const state = reactive({//表格用到的参数
      data: {
        page: 1,
        limit: 10,
        total: outboundOrderData.value.length,
      }
    });
    // loading
    const tableLoading = ref(true)

    //前端限制分页（tableData为当前展示页表格）
    const tableData = () => {
      return outboundOrderData.value
    };
    //改变页码
    const handleCurrentChange = (e) => {
      state.data.page = e;
      handleGetOutboundOrderList(e, state.data.limit)
    };
    //改变页数限制
    const handleSizeChange = (e) => {
      state.data.limit = e;
      handleGetOutboundOrderList(e, state.data.limit)
    };
    const handleGetOutboundOrderList = (page, limit) => {//获取用户列表
      tableLoading.value = true
      const params = {
        pageNum: page,
        pageSize: limit
      }
      getOutboundOrderList(params).then((res) => {
        tableLoading.value = false

        /* 转换数据格式 */
        const tmpArr = []
        if (Array.isArray(res.rows)) {
          res.rows.forEach(item => {
            const tmpWmsOutboundOrderDO = item.wmsOutboundOrderVo
            const details = { detailVOS: item.detailVOS }
            tmpArr.push({ ...item.wmsOutboundOrderVo, ...details })
          })
        }
        outboundOrderData.value = tmpArr
        state.data.total = res.total
      })

    }
    onBeforeMount(() => {
      handleGetOutboundOrderList(state.data.page, state.data.limit)
      getClientList().then((res) => {
        clientList.value = res.rows
      })
      getWarehouseListV2().then((res) => {
        warehouseList.value = res
      })
    })
    onMounted(() => {
      tableFilter.value.forEach(function (item, index) {
        if (item.isSelected) {
          selectedFilters.value.push(item.label)
          outboundDataColumn.value.push(item)
        }
      })
    })

    const onSearch = () => {
      const params = {
        pageSize: state.data.limit,
        pageNum: state.data.page,
        orderCode: searchForm.orderCode,
        clientId: searchForm.clientId,
        warehouseId: searchForm.warehouseId,
        orderType: searchForm.orderType
      }
      getOutboundOrderList(params).then((res) => {
        /* 转换数据格式 */
        const tmpArr = []
        if (Array.isArray(res.rows)) {
          res.rows.forEach(item => {
            const tmpWmsOutboundOrderDO = item.wmsOutboundOrderVo
            const details = { detailVOS: item.detailVOS }
            tmpArr.push({ ...item.wmsOutboundOrderVo, ...details })
          })
        }
        outboundOrderData.value = tmpArr
        state.data.total = res.total
      })
    }

    const handleCheckAllChange = (val) => {//全选按钮
      outboundDataColumn.value = []
      selectedFilters.value = []
      isIndeterminate.value = false;
      if (val) {
        tableFilter.value.forEach(item => {
          item.isSelected = val
          outboundDataColumn.value.push(item)
          selectedFilters.value.push(item.label)
        })
      }

    }
    const handleCheckChange = (val) => {//设置勾选列状态
      let temp = []
      tableFilter.value.forEach(item_t => {
        selectedFilters.value.forEach(item_s => {
          if (item_t.label == item_s) {
            temp.push(item_t)
          }
        })
      })
      if (temp.length < tableFilter.value.length && temp.length > 0) {
        isIndeterminate.value = true
      } else {
        isIndeterminate.value = false
      }
      outboundDataColumn.value = temp
      selectedFilters.value = outboundDataColumn.value.map(item => item.label)
    }
    const printSelectedRows = () => {//直接打印出库单

      if (selectedRows.value.length == 0) {
        ElMessage.warning('请选择要打印的记录')
      } else {
        const printWindow = window.open('', '_blank');
        let content = `<html><head><title>打印</title></head><body>`
        content += `<h1>出库单记录</h1>`
        content += `<table style="border-collapse: collapse; width: 100%;">`;
        content += `<tr>
            <th style="border: 1px solid black; padding: 8px;">出库单单号</th>
            <th style="border: 1px solid black; padding: 8px;">数量</th>
            <th style="border: 1px solid black; padding: 8px;">标签价</th>
            <th style="border: 1px solid black; padding: 8px;">入库时间</th>
            <th style="border: 1px solid black; padding: 8px;">出借客户</th>
            <th style="border: 1px solid black; padding: 8px;">入库仓库</th>
            <th style="border: 1px solid black; padding: 8px;">入库人员</th>
          </tr>`;
        selectedRows.value.forEach(row => {

          content += `<tr>
              <td style="border: 1px solid black; padding: 8px;">${row.orderCode}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.jadeQuantity}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.jadeTagPrice}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.createTime}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.clientName}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.warehouseName}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.createBy}</td>
            </tr>`;
        });
        content += `</table></body></html>`;
        printWindow.document.open();
        printWindow.document.write(content);
        printWindow.document.close();

        printWindow.onload = () => {
          printWindow.print();
          printWindow.close();
        };
        selectedRows.value = []
      }
    }

    //自定义打印入库单
    const designPrint = () => {
      // console.log("这是provider:",provider)
      // 需要一次数据更新
      printDataProp.value = printData
      printShow.value = true;
    }

    const handleChangeSelection = (selection) => {//已勾选的记录
      selectedRows.value = selection
      createElementTypes(selectedRows._rawValue)
      // console.log(selectedRows)
      // console.log(printData)
    }
    const openDetails = (row) => {
      drawer.value = true
      rowDetails.value = row.detailVOS
    }
    const onReset = () => {
      searchForm.jadeCode = searchForm.clientId = searchForm.orderCode = searchForm.warehouseId = searchForm.orderType = ''
    }

    const parseTimestamp = function(timestamp) {
      const dateObject = new Date(timestamp);

      const year = dateObject.getFullYear();
      const month = dateObject.getMonth() + 1; // Months are zero-indexed
      const day = dateObject.getDate();
      const hours = dateObject.getHours();
      const minutes = dateObject.getMinutes();
      const seconds = dateObject.getSeconds();

      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      return formattedDate
    }

    
    const mergeOrder = () => {
      const params = selectedRows.value.map( item => item.id)
      if(selectedRows.value.length > 1 ){        
        mergeOutboundOrder(params).then( (res) => {
          console.log(res);
          if(res.code == 500) {
            ElMessage.error(res.msg)
          } else if(res.code == 200) {
            ElMessage.success(res && res.msg)
            handleGetOutboundOrderList(state.data.page, state.data.limit)
          }
        })
      } else {
        ElMessage.warning('请勾选合并出库单（2条以上）')
      }
    }
    // 导出明细处理
    const handlerExportOrder = () => {
      
    }

    return {
      printShow,providerData,printDataProp,designPrint,//打印的相关变量及方法
      outboundOrderData, clientList,
      searchForm, rowDetails, drawer, warehouseList,
      collapseName, selectedRows, checkAll, isIndeterminate,
      activeNames, tableLoading,
      outboundDataColumn, selectedFilters, tableFilter,
      tableData,
      handleChangeSelection, handleCheckAllChange, handleCheckChange,
      handleCurrentChange, openDetails, onSearch, printSelectedRows, onReset,
      handleSizeChange, handleGetOutboundOrderList,parseTimestamp,mergeOrder,handlerExportOrder,
      ...toRefs(state),
    };
  },
});


</script>
  #F8F8F8
  
<style rel="stylesheet/scss" lang="scss" scoped>
.front {
  background-color: #fff;
  padding: 10px;

  .front-input {
    width: 320px;
  }
}

.el-collapse-item__content {
  border-bottom-width: 0;
}

.center {
  margin-top: 10px;
  // border-top: 1px solid var(--el-border-color);
  // border-bottom: 1px solid var(--el-border-color);
}

.tail {
  background-color: #FFF;
  margin-top: 40px;
  padding: 10px;
}

.tail-action {
  display: flex;
  margin-bottom: 10px;
}


.center .center-data {
  height: 30px;
  width: 150px;
  border: 1px solid;
  border-radius: 10px;
  margin: 10px;
  text-align: center;
  font-size: 20px;
  background-color: #72f6ff;
}

.el-table {
  .el-button {
    margin-left: 0px; //调整按钮不对齐
  }
}
</style>
  